#include <iostream>
#include "uv.h"
//#include "encapsulation/TcpSocket.h"
#include "TcpSocketImpl.h"
#include "encapsulation/TcpServer.h"
#include "encapsulation/Thread.h"

using namespace std;

void read(const char *buf, size_t size, void *userData)
{
    auto tcpSocket = static_cast<TcpSocket *>(userData);
    const string &ip = tcpSocket->peerIp();
    int port = tcpSocket->peerPort();

    std::string str(buf, size);
    std::cout << Thread::getThreadId() << " client ip:" << ip.c_str() << " port:" << port << ",read:" << str.c_str()
              << std::endl;
}

void disconnected(void *userData)
{
    auto tcpSocket = static_cast<TcpSocket *>(userData);
    const string &ip = tcpSocket->peerIp();
    int port = tcpSocket->peerPort();

    std::cout << Thread::getThreadId() << " client ip:" << ip.c_str() << " port:" << port << " disconnected"
              << std::endl;

    delete tcpSocket;
}

void onNewConnect(TcpSocket *tcpSocket, void *userData)
{
    tcpSocket->setOnReadCB(read, static_cast<void *>(tcpSocket));
    tcpSocket->setDisconnectedCB(disconnected, static_cast<void *>(tcpSocket));

    const string &ip = tcpSocket->peerIp();
    int port = tcpSocket->peerPort();

    std::cout << Thread::getThreadId() << " new client ip:" << ip.c_str() << " port:" << port << std::endl;
}

int main()
{
    uv_loop_t *loop = uv_default_loop();

    TcpSocket *tcpSocket = new TcpSocketImpl(loop);
    tcpSocket->setIPAddress("127.0.0.1");
    tcpSocket->setPort(8080);
    tcpSocket->connectToHost();

//    TcpServer *tcpServer = new TcpServer(loop);
//    tcpServer->listen(TcpServer::HostAddress::Any, 8080);
//    tcpServer->setNewConnectCB(onNewConnect, nullptr);

    uv_run(loop, UV_RUN_DEFAULT);

    return 0;
}
